package fpt.edu.vn.action;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

import fpt.edu.vn.dao.AddnewDao;
import fpt.edu.vn.model.Favorites;

/* 
 * AddFavoriteAction.java
 *  
 * 0.1
 * 
 * 10/15/2012 
 *  
 * Copyright notice 
 *  
 * Modification Logs: 
 *   DATE        AUTHOR      DESCRIPTION 
 *  -------------------------------------------------------- 
 *  15-Oct-2012  ThuongND    Create new 
 */
public class AddFavoriteAction extends ActionSupport {

	private static final long serialVersionUID = 1L;

	// For SessionAware
	Map<String, Object> session;

	private int userId;
	AddnewDao adddao = new AddnewDao();
	private Favorites fav = new Favorites();
	private int topicId;
	private InputStream inputStream;

	public String execute() {
		int userId_ = 0;
		session = ActionContext.getContext().getSession();
		if (session.containsKey("userIdss")) {
			userId_ = (Integer) session.get("userIdss");
			setUserId(userId_);
		}
		if (adddao.checkAddFavorite(userId, topicId)) {
			inputStream = toUTF8InputStream("Bài đã có trong yêu thích");
			return SUCCESS;
		} else {
			if (adddao.checkAddFavorite(userId, topicId)) {
				execute();
				inputStream = toUTF8InputStream("Bài đã có trong yêu thích");
				return SUCCESS;

			} else {
				fav.setTopicId(topicId);
				fav.setUsersId(userId);
				adddao.addFavorite(fav);
				inputStream = toUTF8InputStream("Đã thêm");
				return SUCCESS;
			}
		}

	}

	public static InputStream toUTF8InputStream(String str) {
		InputStream is = null;
		try {
			is = new ByteArrayInputStream(str.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// UTF-8 should always be supported
			throw new AssertionError();
		}
		return is;
	}

	public int getUserId() {
		return userId;
	}

	public void setUserId(int userId) {
		this.userId = userId;
	}

	public int getTopicId() {
		return topicId;
	}

	public void setTopicId(int topicId) {
		this.topicId = topicId;
	}

	public InputStream getInputStream() {
		return inputStream;
	}

	public void setInputStream(InputStream inputStream) {
		this.inputStream = inputStream;
	}

}
